import QQMapWX from 'static/common/js/qqmap-wx-jssdk.js';
let qqmapsdk;
let lists = [];
export default {
	data() {
		return {
			fileList1: [],
			//水印变量
			flagC: false,
			canvasWidth: '',
			canvasHeight: '',
			photoIndex: 0,
			address: '' //图片位置
		};
	},
	onLoad() {
		this.getSignInToday();
		//获取经纬度以及当前
		// #ifndef APP-PLUS
		// 实例化API核心类
		qqmapsdk = new QQMapWX({
			//key: '5WNBZ-2JYR6-SPUSL-M3WGH-U4KDT-K2FYV',
			key: 'E5NBZ-VV5CD-IL64J-HW7Q5-H2EQS-VZFVD'
		});
		// #endif
		let _this = this;
		uni.getFuzzyLocation({
			type: 'gcj02', //返回可以用于uni.openLocation的经纬度
			success: res => {
				const latitude = res.latitude;
				const longitude = res.longitude;
				let location = longitude + ',' + latitude;
				console.log('location', JSON.stringify(res));
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: latitude,
						longitude: longitude
					},
					//location: e.detail.value.reverseGeo || '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
					//get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
					success: function(res) {
						//成功后的回调
						console.log('当前位置信息' + JSON.stringify(res));
						_this.address = res.result.address;
					},
					fail: function(error) {
						console.error(error);
					},
					complete: function(res) {
						console.log(res);
					}
				});
			}
		});

	},
	methods: {
		// 删除图片
		deletePic(event) {
			this.fileList1.splice(event.index, 1);
		},
		// 新增图片
		afterRead(event) {
			this.photoIndex = 0;
			lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists = lists.map((item, index) => {
				let info = {
					name: event.name,
					...item,
					status: 'uploading',
					message: '上传中',
					cid: new Date().getTime() + index
				};
				this[`fileList${event.name}`].push(info);
				return info;
			});
			this.callAddWaterMart();
		},
		uploadImg(fileName, filePath, curIndex) {
			//fileName：h5图片没有带后缀，需手动拼上
			// #ifdef H5
			fileName = fileName + '.png';
			// #endif
			let $me = this;
			let access_token = uni.getStorageSync('access_token');
			return new Promise((resolve, reject) => {
				console.log('filePath', filePath, $me.$api.uploadFile)
				uni.uploadFile({
					url: $me.$api.uploadFile,
					filePath,
					name: 'file',
					header: {
						Authorization: access_token
					},
					success: function(res) {
						console.log('res', res)
						if (res.statusCode == 200) {
							resolve(res);
						} else {
							resolve();
						}
					},
					fail: function(err) {
						console.log('上传失败了');
						resolve();
					}
				});
			});
		},

		// 调用添加水印的函数
		callAddWaterMart() {
			this.addWaterMark(() => {
				if (this.photoIndex < lists.length - 1) {
					this.photoIndex++;
					this.callAddWaterMart();
				} else {
					//调用签到接口
					console.log('需要去签到了吗', this.fileList1)
					if (this.fileList1.length > 0) {
						this.AddSignIn()
					}
				}
			});
		},
		// 添加水印
		addWaterMark(callback) {
			this.flagC = false;
			let _this = this;
			uni.getImageInfo({
				// 注意此时的地址是正常的图片地址 以下是给图片添加水印返回新的url地址
				src: lists[_this.photoIndex].url,
				success: res => {
					let canvasWidth = null;
					let canvasHeight = null;
					uni.getSystemInfo({
						success: function(info) {
							console.log(info.pixelRatio);
							_this.canvasWidth = `${res.width / info.pixelRatio}px`;
							_this.canvasHeight = `${res.height / info.pixelRatio}px`;
							canvasWidth = res.width / info.pixelRatio;
							canvasHeight = res.height / info.pixelRatio;
						}
					});
					var ctx = uni.createCanvasContext('myCanvas');
					// 在自定义组件内 需要传递第二参数 this canvas才生效
					ctx.clearRect(0, 0, canvasWidth, canvasHeight);
					ctx.beginPath();
					console.log('lists[_this.photoIndex].url', lists[_this.photoIndex].url)
					ctx.drawImage(lists[_this.photoIndex].url, 0, 0, canvasWidth,
						canvasHeight); // 第一个参数是图片 第二、三是图片在画布位置 第四、五是将图片绘制成多大宽高（不写四五就是原图宽高）

					//这部分是水印的大小位置和数量
					let horizontal = canvasWidth / 4;
					let vertical = canvasHeight / 3;
					let fonstsize = canvasWidth / 30;
					ctx.setFontSize(fonstsize);
					ctx.setFillStyle('rgba(255,255,255,0.8)');
					let height1 = canvasHeight - 100;
					console.log('height1' + height1);
					console.log(_this.address);
					if (_this.address) {
						ctx.fillText(_this.address, 30, height1, fonstsize * 15 * 2);
					}
					let curTime = Number(new Date());
					let formatCurTime = uni.$u.timeFormat(curTime, 'yyyy年mm月dd日 hh时MM分ss秒');
					let height2 = canvasHeight - 50;
					console.log('height2' + height2);
					ctx.fillText(formatCurTime, 30, height2, fonstsize * 15 * 2);

					//ctx.restore();
					// 开始绘制添加水印的图片并显示在页面中
					ctx.draw(false, () => {
						setTimeout(() => {
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas',
								quality: 0.4,
								width: _this.canvasWidth,
								height: _this.canvasHeight,
								destWidth: _this.canvasWidth,
								destHeight: _this.canvasHeight,
								success: canvas2 => {
									console.log(123, canvas2.tempFilePath);
									console.log('图片信息', JSON.stringify(
										canvas2));
									console.log('lists[_this.photoIndex]',
										lists[_this.photoIndex], _this
										.photoIndex)
									lists[_this.photoIndex].url = canvas2
										.tempFilePath;
									lists[_this.photoIndex].thumb = canvas2
										.tempFilePath;
									let namelist = lists[_this.photoIndex].url
										.split(
											'/');
									let id = lists[_this.photoIndex].cid;
									this.uploadImg(namelist[namelist
											.length - 1], lists[_this
											.photoIndex]
										.url).then(res => {
										let index = this.fileList1
											.findIndex(
												item => item
												.cid == id);
										// console.log('id', id, res);
										if (res && res
											.statusCode == 200
										) {
											let result = res
												.data;
											try {
												result = JSON
													.parse(
														result)
													.data
											} catch (error) {
												//TODO handle the exception
											}
											let item = this.fileList1[
												index];
											this.fileList1
												.splice(
													index,
													1,
													Object
													.assign(
														item, {
															status: 'success',
															message: '',
															url: '',
															fileUrl: result
														})
												);
											console.log(lists[
												_this
												.photoIndex
											].name);
											// fileListLen++;
										} else {
											uni.$u.toast(
												'图片上传失败了');
											this.fileList1
												.splice(index,
													1);
										}
										callback();
									});

								}
							});
							// 在自定义组件内 需要传递第二参数 this canvas才生效
							// }, this)
						}, 500);
					});
				}
			});
		},
		AddSignIn() {
			let fileUrlList = [];
			this.fileList1.forEach(item => {
				if (item.status == 'success') {
					console.log('123', item)
					fileUrlList.push(item.fileUrl.split(';')[0])
				}
			})
			this.$postAction(this.$api.AddSignIn, {
				detailId: this.curAccount.detailId,
				url: fileUrlList.join(';')
			}).then(da => {
				uni.showToast({
					title: '签到成功'
				})
			});
		},

	}
};